<?php

namespace app\api\server\order;

use app\api\model\coupon\CouponApiModel;
use app\admin\ServerBase;
use app\api\model\music\MusicWelfareApiModel;
use app\api\model\order\OrderMusicApiModel;
use app\api\model\order\OrderMusicDetailApiModel;
use app\api\model\user\UserCartApiModel;
use app\api\model\user\UserCouponApiModel;
use app\api\model\user\UserGoodsApiModel;
use app\api\model\vip\VipApiModel;
use app\api\validate\order\OrderMusicVal;
use app\logic\model\user\UserCartLogicModel;
use app\logic\model\user\UserGoodsLogicModel;
use app\logic\model\user\UserLogicModel;
use app\logic\single\GoodsSingle;
use app\logic\single\OrderMusicSingle;
use app\logic\single\pay\AliPaySingle;
use app\logic\single\pay\WxPaySingle;
use app\logic\single\WechatSingle;
use Snow\Snow;
use think\facade\Db;
use think\facade\Queue;
use think\Request;

class OrderMusicServer extends ServerBase
{
    protected $model;
    protected $request;
    /**
     * @var mixed
     */
    protected $param;
    /**
     * @var mixed
     */
    private $user_id;
    /**
     * @var UserCouponApiModel
     */
    private $userCouponModel;
    /**
     * @var CouponApiModel
     */
    private $couponModel;
    /**
     * @var OrderMusicDetailApiModel
     */
    private $detailModel;
    /**
     * @var UserCartLogicModel
     */
    private $userCartModel;
    /**
     * @var UserGoodsApiModel
     */
    private $userGoodsModel;
    /**
     * @var MusicWelfareApiModel
     */
    private $MusicWelfareModel;
    /**
     * @var mixed
     */
    private $user_coupon_id;

    function __construct( Request $request)
    {
        $this->request=$request;
        $this->param=$request->param();
        $this->model = new OrderMusicApiModel();
        $this->detailModel = new OrderMusicDetailApiModel();
        $this->validate = new OrderMusicVal();
        $this->userCouponModel = new UserCouponApiModel();
        $this->couponModel = new CouponApiModel();
        $this->user_id = $this->request->user_id;
        $this->userGoodsModel= new UserGoodsApiModel();
        $this->userCartModel = new UserCartLogicModel();
        $this->vipModel = new VipApiModel();
        $this->MusicWelfareModel = new MusicWelfareApiModel();
    }
    function getMyList(){
        [$page,$limit] = $this->getPage($this->param);
        $this->param['user_id']=$this->user_id;
        [$list,$count] = $this->model->getApiList($this->param,[],'*',$page,$limit);
        $result['data']=$list;
        $result['count']=$count;
        $this->getMessageCode('adminMessage.success.select',2);
        return $result;
    }

    function getDetail()
    {
        $id = $this->param['id']??0;
        if(empty($id)){
            $this->getMessageCode('code_common.illegal',1);
            return false;
        }
        //检测订单是否存在
        $order = $this->model->getFindByUserIdAndId($id,$this->user_id);
        if(empty($order)){
            $this->getMessageCode('code_common.not_find',1);
            return false;
        }
        $order['detail'] = $this->detailModel->getByOrderId($order['id']);
        return $order;
    }


    function create(){
        $is_cart= false;
        if(check_request($this->param,'goods_id') || check_request($this->param,'type')){
            //商品详情购买
            if(!$this->validate->scene('create')->check($this->param)){
                $this->ERROR = $this->validate->getError();
                return false;
            }
            $list[] =[
                'goods_id'=>$this->param['goods_id'],
                'type'=>$this->param['type']
            ];
        }
        else{
            //购物车购买
            $is_cart=true;
            $list = UserCartApiModel::where('user_id',$this->user_id)
                ->where('is_select',1)
                ->select()->toArray();
        }
        //判断对应的商品是否存在
        $list = GoodsSingle::getInstance()->getGoodsList($list,true);
        if(empty($list)){
            $this->ERROR = '商品不存在';
            return false;
        }
        $order=[
            'buyer_id'=>$this->user_id,
        ];
        $order_detail=[];
        $order_price = 0;//订单原金额
        //验证商品
        foreach ($list as $key=>$val){
            if(!isset($val['goods']['id'])){
                $this->ERROR = '商品不存在';
                return false;
            }
            $flag = UserGoodsLogicModel::isHave($val['goods_id'],$val['type'],$this->user_id);
            if($flag){
                $this->ERROR = '已拥有商品'.$val['goods']['title'];
                return false;
            }
            if($val['type'] == 20 || $val['type'] == 50){
                $sell_id = $val['goods']['writer']['id'];
                $writer_rate = $val['goods']['writer_rate']??0;
                if($writer_rate <=0){
                    $writer_rate = UserLogicModel::getWriterRate($sell_id);
                }
            }else{
                $sell_id = 0;
                $writer_rate = 0;
            }
            $order_price+=$val['goods']['price'];
            $order_detail[]=[
                'type'=>$val['type'],
                'goods_id'=>$val['goods_id'],
                'sell_id'=>$sell_id,
                'goods_price'=>$val['goods']['price'],
                'writer_price'=>$val['goods']['price'],
                'writer_rate'=>$writer_rate,
            ];
        }
        $pay_price = $order_price;
        //优惠券
        $coupon_id = $this->param['coupon_id']??0;
        $vip_coupon = $this->param['vip_coupon']??0;
        $coupon_price = $this->getCouponPrice($coupon_id,$order_price);
        if($coupon_price === false){
            return false;
        }
        $vip_price = $this->getVipPrice($vip_coupon,$order_price);
        if($vip_price === false){
            return false;
        }
        $all_coupon_price = $coupon_price + $vip_price;
        if($all_coupon_price > 0){
            //支付金额减去优惠券金额
            $pay_price -= $all_coupon_price;
            $order['coupon_id'] = $coupon_id;
            $order['coupon_price'] = $coupon_price;
            $order['vip_price'] = $vip_price;
            $order_detail_count = count($order_detail);
            $single_coupon_price = round($all_coupon_price/$order_detail_count,2);
            foreach ($order_detail as &$val){
                $val['coupon_price']= $single_coupon_price;
            }
            unset($val);
        }

        $order['order_no'] = Snow::createOnlyId();
        $order['pay_price'] = $pay_price;
        $order['order_price'] = $order_price;
        Db::startTrans();
        try {
            $this->model->save($order);
            $order_id = $this->model->id;
            foreach ($order_detail as &$val){
                $val['order_id'] = $order_id;
                $val['writer_price'] = round($val['writer_price'] * $val['writer_rate'] / 100 ,2);
            }
            unset($val);
            if($is_cart){
                $this->userCartModel
                    ->where('user_id',$order['buyer_id'])
                    ->where('is_select',1)
                    ->delete();
            }

            $this->detailModel->saveAll($order_detail);
            //修改优惠券使用状态
            if(!empty($coupon_id)){
                $this->userCouponModel->where('id',$this->user_coupon_id)
                    ->save([
                        'status'=>2,
                        'order_id'=>$order_id,
                    ]);
            }
            $this->getMessageCode('code_common.success',2);
            Queue::later(600,'app\logic\queue\order_music\Cancel',['order_id'=>$order_id],'order_music_cancel');

            Db::commit();
            return $order_id;
        }catch (\Exception $exception){
            Db::rollback();
            $this->ERROR = $exception->getMessage();
            return false;
        }
        return true;
    }
    function create_welfare(){
        $id = $this->param['id']??0;
        if(empty($id)){
            $this->getMessageCode('code_common.illegal',1);
            return false;
        }
        $info = $this->MusicWelfareModel->where('id',$id)
            ->where('status',1)
            ->find();
        if(empty($info)){
            $this->getMessageCode('code_common.illegal',1);
            return false;
        }
        //判断对应的商品是否存在
        $goods = GoodsSingle::getInstance()->getGoods($info['goods_id'],$info['type']);
        if($goods['title'] == '已删除'){
            $this->ERROR = '商品不存在';
            return false;
        }
        $order=[
            'buyer_id'=>$this->user_id,
        ];
        $order_detail=[];
        $flag = UserGoodsLogicModel::isHave($info['goods_id'],$info['type'],$this->user_id);
        if($flag){
            $this->ERROR = '已拥有商品'.$info['goods']['title'];
            return false;
        }
        if($info['type'] == 50){
            $sell_id = $goods['writer']['id'];
        }else{
            $sell_id = 0;
        }
        $order_price=$info['price'];
        $order_detail[]=[
            'type'=>$info['type'],
            'goods_id'=>$info['goods_id'],
            'sell_id'=>0,
            'goods_price'=>$goods['price'],
            'writer_price'=>$goods['price'],
        ];
        $pay_price = $order_price;

        $is_free = 0;
        if($this->request->user['vip_id'] > 0){//如果用户是vip
            $now_time = date('Y-m-d H:i:s');
            if($info['start_time'] < $now_time && $info['end_time'] > $now_time){//如果是正在当期的福利中心商品
                //免费领取
                $is_free = 1;
                $order_price = 0;
            }
        }

        $order['order_no'] = Snow::createOnlyId();
        $order['pay_price'] = $pay_price;
        $order['order_price'] = $order_price;
        Db::startTrans();
        try {
            $this->model->save($order);
            $order_id = $this->model->id;
            foreach ($order_detail as &$val){
                $val['order_id'] = $order_id;
            }
            unset($val);
            $this->detailModel->saveAll($order_detail);
            if($is_free == 1){
                OrderMusicSingle::getInstance()->complete($order_id,40);
            }
            $this->getMessageCode('code_common.success',2);
            Queue::later(600,'app\logic\queue\order_music\Cancel',['order_id'=>$order_id],'order_music_cancel');
            Db::commit();
            return $order_id;
        }catch (\Exception $exception){
            Db::rollback();
            $this->ERROR = $exception->getMessage();
            return false;
        }
        return true;
    }

    function pay(){
        $id = $this->param['id']??0;
        if(empty($id)){
            $this->getMessageCode('code_common.illegal',1);
            return false;
        }
        //检测订单是否存在
        $order = $this->model->getFindByUserIdAndId($id,$this->user_id);
        if(empty($order)){
            $this->getMessageCode('code_common.not_find',1);
            return false;
        }
        if($order['status'] != 10){
            $this->ERROR = '该订单不能支付';
            return false;
        }
        $terminal = $this->param['terminal']??'h5';
        $data=[];
        //获取名称
        $details = $this->detailModel->getByOrderId($order['id']);
        $goodsList = GoodsSingle::getInstance()->getGoodsList($details);
        $user = UserLogicModel::getInfoById($order['buyer_id']);
        $order['openid'] = $user['openid'];
        $title = '';
        $i = 0;
        foreach ($goodsList as $val){
            if($i ==0){
                $title.=$val['goods']['title'];
            }else{
                $title.=','.$val['goods']['title'];
            }
            $i++;
        }
        //todo 微信支付
        $res= WxPaySingle::getInstance()->pay($order,$terminal,'music',$title);
        $data['wx_'.$terminal] = $res;
        //支付宝支付
        $res= AliPaySingle::getInstance()->pay($order,$terminal,'music',$title,$this->param['ali_quit_url']??'',$this->param['ali_return_url']??'');
        $data['ali_'.$terminal] = $res;

        return $data;
    }
    function payByScore(){
        $id = $this->param['id']??0;
        if(empty($id)){
            $this->getMessageCode('code_common.illegal',1);
            return false;
        }
        //检测订单是否存在
        $order = $this->model->getFindByUserIdAndId($id,$this->user_id);
        if(empty($order)){
            $this->getMessageCode('code_common.not_find',1);
            return false;
        }
        if($order['status'] != 10){
            $this->ERROR = '该订单不能支付';
            return false;
        }
        if($this->request->user['score'] < $order['pay_price']){
            $this->ERROR = '积分不足';
            return false;
        }
        $res = OrderMusicSingle::getInstance()->complete($id,30);
        if($res[0] == -1){
            $this->ERROR = $res[1];
            return false;
        }
        return true;
    }

    function cancel(){
        $id = $this->param['id']??0;
        if(empty($id)){
            $this->getMessageCode('code_common.illegal',1);
            return false;
        }
        //检测订单是否存在
        $order = $this->model->getFindByUserIdAndId($id,$this->user_id);
        if(empty($order)){
            $this->getMessageCode('code_common.not_find',1);
            return false;
        }
        $res = OrderMusicSingle::getInstance()->cancle($id);
        if(is_string($res)){
            $this->ERROR=$res;
            return false;
        }else{
            return true;
        }
    }
    function have(){
        [$page,$limit] = $this->getPage($this->param);
        $list = $this->userGoodsModel->getList($this->user_id,$page,$limit,false,true);

        return $list;
    }


    private function getVipPrice($vip_coupon, $order_price)
    {
        $vip_id = $this->request->user['vip_id'];
        if($vip_coupon == 1){
            if($vip_id == -1){
                $this->ERROR = '不是vip用户,不能使用vip折扣';
                return false;
            }
            $vip = $this->vipModel->getFindById($vip_id);
            if(empty($vip)){
                $this->ERROR = 'vip不存在';
                return false;
            }
            return round($order_price * $vip['discount'] / 100 , 2);
        }else{
            return 0;
        }

    }

    private function getCouponPrice($coupon_id, $order_price)
    {
        $coupon['price']=0;
        if(!empty($coupon_id)){
            $user_coupon = $this->userCouponModel->getFindById($coupon_id,$this->user_id);
            if(empty($user_coupon)){
                $this->ERROR = '未找到优惠券';
                return false;
            }
            if($user_coupon['status'] == -1 || date('Y-m-d H:i:s') > $user_coupon['expire_time']){
                $this->ERROR = '优惠券已过期';
                return false;
            }
            if($user_coupon['status'] == 2){
                $this->ERROR = '优惠券已使用';
                return false;
            }
            //查询优惠券是否过期
            $coupon = $this->couponModel->getFindById($user_coupon['coupon_id']);
            if(empty($coupon)){
                $this->ERROR = '未找到优惠券';
                return false;
            }
            //使用条件
            if($order_price < $coupon['enough_price']){
                $this->ERROR = '未达到该优惠券使用金额';
                return false;
            }
            $this->user_coupon_id = $user_coupon['id'];
        }
        return $coupon['price'];
    }
}